package com.samsung.sharepoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

/* This class listens to any chat message sent through TCP protocol. 
 *  It starts a thread which keep listening to incoming messages and 
 *  send those messages as broadcast intent to BroadcastReceiver in Activity "SampleTCP.java"
 */

public class ServiceClass extends Service implements Runnable{
	
	private int PORT=5587;
	Socket s=null;
	ServerSocket ss=null;
	String mClientMsg = "";
	String senderName;
	public static final String BROADCAST_ACTION = "com.samsung.sharepoint.msgsend";
	protected static final int MSG_ID = 0x1337;
	SharedPreferences spref;
	boolean check=true;
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d("ServiceClass","onStartCommand() begin");
		spref= getSharedPreferences("abc",MODE_PRIVATE);
		senderName=spref.getString("name","Anonymous Pundit");
		Thread t=new Thread(this);
		t.start();
		return super.onStartCommand(intent, flags, startId);
	}

	private InetAddress getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();

				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr
						.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress;
						
					}

				}
			}
		} catch (SocketException ex) {
			Log.e("ServerActivity", ex.toString());
		}
		return null;
	}
	
	@Override
	public IBinder onBind(Intent arg0) {

		return null;
	}
	
	public void run(){
		try {
            ss = new ServerSocket(PORT );
		} catch (IOException e) {
            e.printStackTrace();
		}
		Log.d("ServiceClass","About to enter while loop");
		while(!Thread.currentThread().isInterrupted()){
			Message m = new Message();
            m.what = MSG_ID;
			try {
				
					s = ss.accept();
				if(!s.getInetAddress().equals(getLocalIpAddress())){
					check = true;
				}
				Log.d("ServiceClass", "In while loop");
				InputStream is = s.getInputStream();
				if (is != null) {
					BufferedReader input = new BufferedReader(
							new InputStreamReader(is));
					Log.d("ServiceClass", "Got BufferedReader " + s.toString());
					String reader = input.readLine();
					mClientMsg = reader;
					if (!mClientMsg.isEmpty()) {
						Log.d("ServiceClass", "Message Received"
								+ mClientMsg);
						Intent intent = new Intent(BROADCAST_ACTION);
						intent.putExtra("Message", mClientMsg);
						intent.putExtra("MsgSenderName", senderName);
						Log.d("ServiceClass", "Got BufferedReader String ==== "
								+ mClientMsg + " ===CHeck===" + check);
						//To pass it to its own app's broadcast receiver
						sendBroadcast(intent);
						
						String senderIp= s.getInetAddress().getHostAddress();
						 
						// To open its SampleTCP, if other app initiate the chat
						// To the SampleTCP Activity, it needs to pass, invoking app's IP Address and message received
						 if(check && !senderIp.equals(getLocalIpAddress().getHostAddress().toString())){
							 check=false;
							 			 
							 Intent StartChatActivityOnReceivingMsg=new Intent("com.samsung.activity.SampleTCP");
							 StartChatActivityOnReceivingMsg.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		 					 StartChatActivityOnReceivingMsg.putExtra("FirstMessage", mClientMsg);
							 StartChatActivityOnReceivingMsg.putExtra("MsgSenderName", senderName);
							 //On Server Side we are passing to intent, it's own address and client's address
							 StartChatActivityOnReceivingMsg.putExtra("FirstMsgSenderIP",senderIp);
							 String name = mClientMsg.substring(0, mClientMsg.indexOf(":"));
							 StartChatActivityOnReceivingMsg.putExtra("SampleTCP_UserName_Receiver", name);
							 Log.d("ServiceClass", "starting activity");
							 Log.d("ServiceClass", "MANU + " + mClientMsg);
							 Log.d("ServiceClass",senderIp);
							 startActivity(StartChatActivityOnReceivingMsg);
							 Log.d("ServiceClass","Broadcast sent");
						 }
					  }
					  else {
						Log.d("ServiceClass", "Got BufferedReader is empty");
					  }
					
					
				}
				else{
					Log.d("SeriveClass","InputStreamEmpty");
				}
			}
			catch (IOException e) {
					Log.d("ServiceClass","IOEXCEPTION");
					e.printStackTrace();
			}
			catch(NullPointerException n){
			}
		}
	}
	
	public void onDestroy(){

		super.onDestroy();
	}
}
